import {Observer} from "@/utils/observer/Observer";
import {resetLongToStr} from "@/utils/biz/common/BizUtils";

/**
 * 消息观察者 -- 特制消息封装
 */
class MarkLayerObserverBiz extends Observer {
  constructor(self, deviceInfo = {}, item) {
    super();
    // 外部组件
    this.deviceInfo = deviceInfo;
    this.catcheInfo = self;
    this.currentInfo = item;

    // 私有数据
    this.isOpen = false;
  }

  /**
   * 消息监听入口
   * @param bizType
   * @param msgContent
   */
  async update(bizType, msgContent) {
    let self = this.catcheInfo;
    try {
      switch (bizType) {
        case "openMsgWin":
          this.openMsgWin(msgContent);
          break;
        case "closeMsgWin":
          this.closeMsgWin(msgContent);
          break;
        case this.catcheInfo.msgRegisterMark:
          // 特制消息弹窗逻辑
          if ("1" !== msgContent.hasTemplateCall) {
            await this.msgNextSet(msgContent);
          }
          break;
      }
    } catch (e) {
      console.error("消息数据加载失败：" + msgContent)
      self.handleException("sdkBizServices", "安卓消息消费异常 -- " + bizType + " -- >", JSON.stringify(e.stack));
    }
  }

  /**
   * 初始化
   */
  init() {
    let self = this.catcheInfo;
    if (self.msgRegisterMark != "") {
      this.isOpen = true;
    }
  }


  /**
   * 消息处理
   * @param str
   */
  async msgNextSet(str) {
    const obj = JSON.parse(resetLongToStr(str));
    // 判定是特制消息 需要给安卓推送消息
    obj.hasTemplateCall = "1";
    let self = this.catcheInfo;
    // 开启语音播报
    if (self.msgRegisterMarkLayer.hasOpenVideo || self.msgRegisterMarkLayer.hasOpenLayer) {
      try {
        let str = JSON.stringify({
          action: "CommonAction",
          callback: "",
          bizFun: "templateCall",
          data: JSON.stringify(obj)
        });
        await parent.window.android.handleMessage(str);
      } catch (e) {
        console.log(e);
      }
    }

  }

  /**
   * 开启弹窗
   * @param data
   */
  openMsgWin(str) {
    let self = this.catcheInfo;
    try {
      // 判断消息类型
      if (this.isOpen === true) {
        const obj = JSON.parse(resetLongToStr(str));
        // 是不是同一个特制消息
        if (obj.msgCode != self.msgRegisterMark) {
          return;
        }
        // 是不是开启了
        self.msgRegisterMarkLayer.msgWinData.data = obj.msgContent;
        // 配置是否展示就诊弹窗/候诊弹窗
        self.msgRegisterMarkLayer.hasCallShow = !!(obj.msgContent.treatingAlert || obj.msgContent.waitingAlert);
      }
    } catch (e) {
      self.handleException("sdkBizServices", "CommonTimeDateUtil -> openMsgWin -- 开启弹窗 -- >", JSON.stringify(e.stack));
    }
  }

  /**
   * 关闭弹窗
   * @param data
   */
  closeMsgWin(str) {
    let self = this.catcheInfo;
    try {
      // 判断消息类型
      if (self.msgRegisterMark != "") {
        // 配置是否展示就诊弹窗/候诊弹窗
        self.msgRegisterMarkLayer.hasCallShow = false;
      }
    } catch (e) {
      self.handleException("sdkBizServices", "CommonMarkLayerUtil -> closeMsgWin -- 关闭弹窗 -- >", JSON.stringify(e.stack));
    }
  }

}

export {MarkLayerObserverBiz};
